<template>

    <a-modal v-model:visible="visible" :ok-loading="loading" @cancel="handleCancel" @before-ok="handleBeforeOk"
        :unmount-on-close="true" :hide-cancel="false" :closable="true">
        <template #title>
            {{ props.title }}
        </template>
        <a-spin :loading="loading" tip="正在提交请稍后 ...">
            <a-form :model="props.formData" ref="formRef" auto-label-width :rules="props.rules">
                <slot :formData="props.formData"></slot>
            </a-form>
        </a-spin>
    </a-modal>

</template>

<script setup lang="ts">
const visible = ref(false)
const formRef = ref()
const loading = ref(false)
interface Props {
    title: string
    formData?: any
    rules?: any
}

const emits = defineEmits<{
    (e: 'submit', value: any): void
    (e: 'cancel'): void
}>()
const props = withDefaults(defineProps<Props>(), {
    title: '',
    formData: {},
    rules: {}
})


const open = () => {
    visible.value = true
}

const resetForm = () => {
    if (formRef.value) {
        // 重置表单字段
        formRef.value.resetFields()
        // 清空所有数据
        Object.keys(props.formData).forEach(key => {
            const value = props.formData[key];
            if (typeof value === 'string') {
                props.formData[key] = '';
            } else if (Array.isArray(value)) {
                props.formData[key] = [];
            } else if (typeof value === 'number' && key === 'id') {
                props.formData[key] = null;
            } else if (typeof value === 'boolean') {
                props.formData[key] = false;
            } else if (value === null) {
                props.formData[key] = null;
            } else if (typeof value === 'undefined') {
                props.formData[key] = undefined;
            } else if (typeof value === 'symbol') {
                props.formData[key] = Symbol();
            } else if (typeof value === 'object' && value !== null) {
                props.formData[key] = {};
            }
        });

    }
}

const close = async () => {
    visible.value = false
    // 等待弹窗关闭动画完成
    await nextTick()
    resetForm()
}

const closeLoading = () => {
    loading.value = false

}

const handleCancel = async () => {
    visible.value = false
    // 等待弹窗关闭动画完成
    await nextTick()
    resetForm()
    loading.value = false
    emits('cancel')
}

const handleBeforeOk = async (done: (closed: boolean) => void) => {
    try {
        loading.value = true
        const valid = await formRef.value?.validate()
        if (valid === undefined) {
            // 验证通过
            emits('submit', props.formData)
            // 这里不直接关闭弹窗，让父组件控制关闭
            done(false)
        } else {
            loading.value = false
            done(false)
        }
    } catch (error) {
        loading.value = false
        done(false)
    }
}

const setFormData = (data: Record<string, any>) => {
    if (!data) return
    console.log('data', data)
    // 等待弹窗和表单挂载完成
    nextTick(() => {
        if (formRef.value) {
            // 转换为 setFields 所需的格式
            const fieldsData = Object.entries(data).reduce((acc, [key, value]) => {
                if (value !== undefined && value !== null) {
                    acc[key] = { value }
                }
                return acc
            }, {} as Record<string, { value: any }>)

            formRef.value.resetFields()
            formRef.value.setFields(fieldsData)
        }
    })
}

defineExpose({
    open,
    close,
    setFormData,
    closeLoading
})

</script>

<style scoped>
.arco-spin {
    display: block !important;
}
</style>
